﻿package net.wangit.framework.config;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import net.wangit.Path;
import net.wangit.framework.exception.ConfigurationException;
import net.wangit.util.Checker;
import net.wangit.util.XMLUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;


public class UploadSettings {

	private static final Log log = LogFactory
			.getLog(net.wangit.framework.config.UploadSettings.class);
	private static long MAXSIZE = 0x200000L;
	private static UploadConfig config;

	public UploadSettings() {
	}

	public static void load() {
		config = new UploadConfig();
		Set allowedTypes = new HashSet();
		Set allowedExtensions = new HashSet();
		String path = (new StringBuilder(String.valueOf(Path.getHomePath())))
				.append("/upload.xml").toString();
		try {
			Document document = XMLUtil.parseByPath(path);
			Element root = document.getRootElement();
			config.setMaxSize(XMLUtil.getTextLong(root, "maxSize", MAXSIZE));
			List list = root.element("allowedTypes").elements("contentType");
			if (!Checker.isEmpty(list)) {
				for (int i = 0; i < list.size(); i++)
					allowedTypes.add(((Element) list.get(i)).getText().trim());

			}
			config.setAllowedTypes(allowedTypes);
			list = root.element("allowedExtensions").elements("extension");
			if (!Checker.isEmpty(list)) {
				for (int i = 0; i < list.size(); i++)
					allowedExtensions.add((new StringBuilder(".")).append(
							((Element) list.get(i)).getText().trim())
							.toString());

			}
			config.setAllowedExtensions(allowedExtensions);
		} catch (Exception e) {
			log.error((new StringBuilder("could not load beans: "))
					.append(path).toString(), e);
			throw new ConfigurationException((new StringBuilder(
					"could not load upload: ")).append(path).toString(), e);
		}
	}

	public static UploadConfig getConfig() {
		return config;
	}

}
